package java8.optional.demo01;

import java8.optional.Insurance;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.util.Objects;

/**
 * @author ChangLiang
 * @date 2020/4/21
 */
public class AppTest {

    @Test
    @DisplayName("test NPE")
    public void test() {
        String insuranceName = getInsuranceName(null);
        System.out.println(insuranceName);

        String insuranceName1 = getInsuranceName(new Person());
        System.out.println(insuranceName1);
    }

    /**
     * 方法1：这样调用中间有一个环节空指针 就空指针了
     * @param person
     * @return
     */
    private String getInsuranceName(Person person) {
        return person.getCar().getInsurance().getName();
    }

    @Test
    @DisplayName("test NPE with deep doubts")
    public void test2(){
        String insuranceNameByDeepDoubts = getInsuranceNameByDeepDoubts(null);
        // output: UNKNOWN
        System.out.println(insuranceNameByDeepDoubts);

        String insuranceNameByDeepDoubts1 = getInsuranceNameByDeepDoubts(new Person());
        // output: UNKNOWN
        System.out.println(insuranceNameByDeepDoubts1);
    }

    /**
     * 方法2：if-else嵌套判断
     * @param person
     * @return
     */
    private String getInsuranceNameByDeepDoubts(Person person) {
        if (Objects.nonNull(person)) {
            Car car = person.getCar();
            if (Objects.nonNull(car)) {
                Insurance insurance = car.getInsurance();
                if (Objects.nonNull(insurance)) {
                    return insurance.getName();
                }
            }
        }
        return "UNKNOWN";
    }

    @Test
    @DisplayName("test 卫语句")
    public void test3() {
        String name = getInsuranceNameByMultiExit(null);
        System.out.println(name);

        String name1 = getInsuranceNameByMultiExit(new Person());
        System.out.println(name1);
    }

    /**
     * 方法3：使用卫语句 避免嵌套的if-else
     * @param person
     * @return
     */
    private String getInsuranceNameByMultiExit(Person person) {
        final String defaultValue = "UNKNOWN";
        if (Objects.isNull(person)) {
            return defaultValue;
        }
        Car car = person.getCar();
        if (Objects.isNull(car)) {
            return defaultValue;
        }
        Insurance insurance = car.getInsurance();
        if (Objects.isNull(insurance)) {
            return defaultValue;
        }
        return insurance.getName();
    }
}
